package top.myhdg.bijou.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.util.ArrayList;
import java.util.List;

import top.myhdg.bijou.R;
import top.myhdg.bijou.sqlite.Bookmark;
import top.myhdg.bijou.sqlite.BookmarkDao;

public class BookmarkActivity extends BaseActivity {
    ArrayList<BookmarkItem> bookmarkItems;
    List<Bookmark> bookmarkList;
    BookmarkDao bookmarkDao;
    BookmarkAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bookmark);

        Intent intent = getIntent();
        final String frontTitle = intent.getStringExtra("Title");
        final String frontWebsite = intent.getStringExtra("Website");

        ListView bookmarkListView = findViewById(R.id.bookmarkList);
        bookmarkListView.setVerticalScrollBarEnabled(false);//隐藏普通滚动条
        bookmarkListView.setFastScrollEnabled(false);//隐藏快速滚动条

        //==========获取数据并显示==========
        bookmarkDao = new BookmarkDao(BookmarkActivity.this);
        bookmarkList = new ArrayList<>();
        bookmarkItems = new ArrayList<>();
        adapter = new BookmarkAdapter(BookmarkActivity.this, R.layout.item_bookmark, bookmarkItems);
        bookmarkListView.setAdapter(adapter);
        if (bookmarkDao.isDataExist()) {
            bookmarkList = bookmarkDao.getAllDate();
            initBookmarks();
        }
        bookmarkListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.putExtra("Bookmark", bookmarkList.get(position).getWebsite());
                setResult(2, intent);
                BookmarkActivity.this.finish();
            }
        });
        bookmarkListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                new BookmarkDialog(BookmarkActivity.this, R.style.dialogTheme,
                        bookmarkList.get(position).getTitle(),
                        bookmarkList.get(position).getWebsite(),
                        new BookmarkDialog.SureListener() {
                            @Override
                            public void getBookmark(String title, String website) {
                                Bookmark oldBookmark = bookmarkList.get(position);
                                Bookmark newBookmark = new Bookmark(title, website);
                                bookmarkList.set(position, newBookmark);
                                bookmarkDao.updateBookmark(oldBookmark, newBookmark);
                                initBookmarks();
                                adapter.notifyDataSetChanged();
                            }
                        }, "修改书签").show();
                return true;
            }
        });
        //==========获取数据并显示==========

        ImageButton addBookmark = findViewById(R.id.addBookmark);
        addBookmark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new BookmarkDialog(BookmarkActivity.this, R.style.dialogTheme, frontTitle, frontWebsite,
                        new BookmarkDialog.SureListener() {
                            @Override
                            public void getBookmark(String title, String website) {
                                Bookmark bookmark = new Bookmark(title, website);
                                bookmarkList.add(bookmark);
                                initBookmarks();
                                bookmarkDao.insertDate(bookmark);
                                adapter.notifyDataSetChanged();
                            }
                        }, "添加书签").show();
            }
        });

        ImageButton emptyBookmark = findViewById(R.id.emptyBookmark);
        emptyBookmark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new QMUIDialog.MessageDialogBuilder(BookmarkActivity.this)
                        .setTitle("请确认")
                        .setMessage("删除所有书签？")
                        .addAction("取消", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                dialog.dismiss();
                            }
                        })
                        .addAction(0, "删除", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                for (int i = 0; i < bookmarkList.size(); i++) {
                                    bookmarkDao.deleteBookmark(bookmarkList.get(i));
                                }
                                bookmarkList.clear();
                                bookmarkItems.clear();
                                adapter.notifyDataSetChanged();
                                dialog.dismiss();
                            }
                        })
                        .create().show();
            }
        });

        Button exitBookmark = findViewById(R.id.exitBookmark);
        exitBookmark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BookmarkActivity.this.finish();
            }
        });
    }

    private void initBookmarks() {
        bookmarkItems.clear();
        for (final Bookmark bookmark : bookmarkList) {
            final int itemId = bookmarkList.indexOf(bookmark);
            String title = bookmark.getTitle();
            String website = bookmark.getWebsite();
            bookmarkItems.add(new BookmarkItem(itemId, title, website, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new QMUIDialog.MessageDialogBuilder(BookmarkActivity.this)
                            .setTitle("请确认")
                            .setMessage("删除选中书签？")
                            .addAction("取消", new QMUIDialogAction.ActionListener() {
                                @Override
                                public void onClick(QMUIDialog dialog, int index) {
                                    dialog.dismiss();
                                }
                            })
                            .addAction(0, "删除", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                                @Override
                                public void onClick(QMUIDialog dialog, int index) {
                                    Bookmark bookmarkD = bookmarkList.get(itemId);
                                    bookmarkDao.deleteBookmark(bookmarkD);
                                    bookmarkItems.remove(itemId);
                                    bookmarkList.remove(bookmarkD);
                                    adapter.notifyDataSetChanged();

                                    dialog.dismiss();
                                }
                            })
                            .create().show();

                }
            }));
        }
    }

    //=====书签Dialog=====
    static class BookmarkDialog extends Dialog {
        private String title;
        private String website;
        private SureListener sureListener;
        private String text;

        EditText titleEdit;
        EditText websiteEdit;
        Button sure;
        TextView titleBar;

        BookmarkDialog(@NonNull Context context, int themeResId, String title, String website, SureListener sureListener, String text) {
            super(context, themeResId);
            this.title = title;
            this.website = website;
            this.sureListener = sureListener;
            this.text = text;
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //==========设置更改UADialog位置及动画==========
            Window window = getWindow();
            assert window != null;
            window.setGravity(Gravity.CENTER); // 设置dialog显示位置
            window.setWindowAnimations(R.style.zoom_animation); // 添加动画效果
            setContentView(R.layout.dialog_bookmark);
            setCanceledOnTouchOutside(false);// 点击Dialog外部消失
            //==========设置更改UADialog位置及动画==========

            titleEdit = findViewById(R.id.bookmarkTitleEdit);
            titleEdit.setText(title);
            websiteEdit = findViewById(R.id.bookmarkWebsiteEdit);
            websiteEdit.setText(website);
            sure = findViewById(R.id.addNewBookmark);
            titleBar = findViewById(R.id.titleBar);
            sure.setText(text);
            titleBar.setText(text);
            sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sureListener.getBookmark(titleEdit.getText().toString(), websiteEdit.getText().toString());
                    BookmarkDialog.this.dismiss();
                }
            });
            Button cancel = findViewById(R.id.exitAddBookmark);
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    BookmarkDialog.this.dismiss();
                }
            });
        }

        public interface SureListener {
            void getBookmark(String title, String website);
        }
    }
}

class BookmarkItem {
    private int itemId;
    private String bookmarkTitle;
    private String bookmarkWebsite;
    private View.OnClickListener onClickListener;

    BookmarkItem(int itemId, String bookmarkTitle, String bookmarkWebsite, View.OnClickListener onClickListener) {
        this.itemId = itemId;
        this.bookmarkTitle = bookmarkTitle;
        this.bookmarkWebsite = bookmarkWebsite;
        this.onClickListener = onClickListener;
    }

    int getItemId() {
        return itemId;
    }

    String getBookmarkTitle() {
        return bookmarkTitle;
    }

    String getBookmarkWebsite() {
        return bookmarkWebsite;
    }

    View.OnClickListener getOnClickListener() {
        return onClickListener;
    }
}

class BookmarkAdapter extends ArrayAdapter<BookmarkItem> {
    private int resourceId;

    BookmarkAdapter(@NonNull Context context, int resourceId, ArrayList<BookmarkItem> objects) {
        super(context, resourceId, objects);
        this.resourceId = resourceId;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        BookmarkItem bookmarkItem = getItem(position);
        View view;
        ViewHolder viewHolder;
        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(resourceId, null);
            viewHolder = new ViewHolder();
            viewHolder.bookmarkTitle = view.findViewById(R.id.bookmarkTitle);
            viewHolder.bookmarkWebsite = view.findViewById(R.id.bookmarkWebsite);
            viewHolder.deleteBookmark = view.findViewById(R.id.deleteBookmark);
            view.setTag(viewHolder); // 将ViewHolder存储在View中
        } else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag(); // 重新获取ViewHolder
        }
        assert bookmarkItem != null;
        int pageId = bookmarkItem.getItemId() + 1;
        String pageTitle = pageId + ". " + bookmarkItem.getBookmarkTitle();
        viewHolder.bookmarkTitle.setText(pageTitle);
        viewHolder.bookmarkWebsite.setText(bookmarkItem.getBookmarkWebsite());
        viewHolder.deleteBookmark.setOnClickListener(bookmarkItem.getOnClickListener());
        return view;
    }

    class ViewHolder {
        TextView bookmarkTitle;
        TextView bookmarkWebsite;
        ImageButton deleteBookmark;
    }
}